<?php
//by willson 105328468@qq.com 2014/9/3
//app interface
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('ROOT_PATH', dirname(__FILE__));
define('FRAMEWORK_PATH', ROOT_PATH . '/framework');
define('PROTECTED_PATH', ROOT_PATH . '/protected');
define('APP_PATH', PROTECTED_PATH . '/api');
define('MODEL_PATH', PROTECTED_PATH . '/model');
define('UPLOAD_PATH', '/uploadfiles');
require_once(FRAMEWORK_PATH . '/class/request/request.php');
require_once(PROTECTED_PATH . '/config.php');
require_once(FRAMEWORK_PATH . '/global.php');
require_once(FRAMEWORK_PATH . '/wenyan.php');
require_once(APP_PATH . '/core.php');
require_once(MODEL_PATH . '/base.model.php');
require_once(FRAMEWORK_PATH . '/class/smarty-3.1.18/libs/Smarty.class.php');
require_once(FRAMEWORK_PATH . '/class/wxapi/config.php');
require_once(FRAMEWORK_PATH . '/class/wxapi/jssdk.php');
require_once(FRAMEWORK_PATH . '/class/rsa/rsa.php'); //rsa数据加密

if (!get_magic_quotes_gpc()) {
    $_GET   = addslashes_deep($_GET);
    $_POST  = addslashes_deep($_POST);
    $_COOKIE = addslashes_deep($_COOKIE);
    $_SERVER = addslashes_deep($_SERVER);
}
$request = new Request();


if (isMobile()){
    define('TEMPLATE_PATH', PROTECTED_PATH . '/template/wap');
    //初始化smarty
    $smarty = new Smarty();
    $smarty->setTemplateDir(TEMPLATE_PATH);
    $smarty->setCompileDir(ROOT_PATH . '/temp/templates_c/wap/');
    $smarty->setCacheDir(ROOT_PATH . '/temp/cache/wap/');
}else {
    define('TEMPLATE_PATH', PROTECTED_PATH . '/template/pc');
    //初始化smarty
    $smarty = new Smarty();
    $smarty->setTemplateDir(TEMPLATE_PATH);
    $smarty->setCompileDir(ROOT_PATH . '/temp/templates_c/pc/');
    $smarty->setCacheDir(ROOT_PATH . '/temp/cache/pc/');
}


//default return json array
$json = array(
	"data" => null,
	"msg_type" => 0,
	"msg" => "成功",
	"error" => 0
);

$app = isset($_GET['app']) ? strtolower(trim($_GET['app'])) : 'home';
$act = isset($_GET['act']) ? strtolower(trim($_GET['act'])) : 'index';
$tpl = isset($_GET['tpl']) ? strtolower(trim($_GET['tpl'])) : '';
if (preg_match('/^[a-z0-9._]+$/', $tpl)) {
	success('ok');
} else if (preg_match("/^[a-zA-Z0-9_.-]+$/", $app) && preg_match("/^[a-zA-Z0-9_.-]+$/", $act)) {
	//security check file and function
	$file = APP_PATH."/{$app}.php";
	if (file_exists($file)) {
		require_once($file);
		if (class_exists($app)) {
		    $class = new $app();
		    if (method_exists($class, $act)) {
		    	$class->$act();
		    } else {
		    	error_tip('Missing method');
		    }
		} else {
			error_tip('Missing controller');
		}
	} else {
		error_tip('Missing file');
	}
} else {
	error_tip('Wrong file');
}

//trigger error, exit
function error($msg, $msg_type=0, $error=1) {
	global $json;
	global $app, $act, $smarty;
	$json['error'] = $error;
	$json['msg_type'] = $msg_type;
	$json['msg'] = $msg;
	//重新登录
	if ($msg_type==-100) {
		//登录注册后跳转链接
		$url = (isset($_REQUEST['url']) && trim($_REQUEST['url'])) ? $_REQUEST['url'] : '';
		if (!$url) {
			$u = substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1);

			if($_SERVER['QUERY_STRING']!='')$u .= '?'.$_SERVER['QUERY_STRING'];
			$url = $u;
		}
		$url = urlencode($url);
            header("Location: /wap.php?tpl=login&url={$url}");
            exit;
	}
	//AJAX请求,bodyView的时候用
	if(isset($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"){
		die(json_encode($json));
	}
	//商品下架
	if ($msg_type==-99) {
		//登录注册后跳转链接
		//header("Location: /wap.php?tpl=passport.login&goto={$goto}");
		echo '<meta charset="UTF-8"><script>alert("该商品已经被抢光，库存不足已下架。");self.location="wap.php";</script>';
		exit;
	}
	if ($msg_type==-88) {
		//跳转首页
		header("Location: /wap.php");
		// echo '<meta charset="UTF-8"><script>alert("该商品已经被抢光，库存不足已下架。");self.location="wap.php";</script>';
		exit;
	}
	$errorto = (isset($_REQUEST['errorto']) && trim($_REQUEST['errorto'])) ? $_REQUEST['errorto'] : '';
	if ($errorto!='') {
		$html = "<meta charset='UTF-8'><script>alert('{$msg}');";
		$sign = '';
		if (isset($_SESSION['member'])) $sign = isset($_SESSION['member']->sign) ? $_SESSION['member']->sign : '';
		$errorto = str_replace('<#sign#>', $sign, $errorto);
		if (stripos($errorto, 'history.back()')!==false || stripos($errorto, 'history.go(-1)')!==false) {
			$errorto = stripcslashes($errorto);
			$html .= $errorto;
		} else {
			$errorto = stripcslashes($errorto);
			$html .= 'location.href="'.$errorto.'"';
		}
		$html .= '</script>';
		exit($html);
	}
	switch ($msg_type) {
		case -9:
			echo "<meta charset='UTF-8'><script>alert('{$msg}');location.href='api.php?app=passport&act=logout&gourl=".urlencode('wap.php?app=member&act=index')."';</script>";
			break;
		case -1:
			echo "<meta charset='UTF-8'><script>alert('{$msg}');location.href='wap.php';</script>";
			break;
		default:
			echo "<meta charset='UTF-8'><script>alert('{$msg}');history.back();</script>";
			break;
	}
	exit;
}

//success and exit
function success($data, $msg='成功', $msg_type=0, $element=array(), $gourl='', $goalert='') {
	global $json;
	global $app, $act, $smarty;
	if (substr($_SERVER['REQUEST_URI'], -8)=='/wap.php') {
		$template_file = "{$app}.{$act}.html";
	} else {
		$tpl = (isset($_GET['tpl']) && trim($_GET['tpl'])) ? trim($_GET['tpl']) : '';
		if (preg_match('/^[a-z0-9._]+$/', $tpl)) {
			$template_file = "{$tpl}.html";
		} else {
			$template_file = "{$app}.{$act}.html";
		}
	}
	if (file_exists(TEMPLATE_PATH.'/'.$template_file)) {
		$sign = '';
		if (isset($_SESSION['member']) && isset($_SESSION['member']->id)) {
			$smarty->assign('logined', 1);
			$_SESSION['member'] = add_domain_deep($_SESSION['member'], array("avatar"));
			$_SESSION['member']->reg_time_word = date('Y-m-d', $_SESSION['member']->reg_time);
			$smarty->assign('member', $_SESSION['member']);
			if (isset($_SESSION['member']->sign)) $sign = $_SESSION['member']->sign;
		} else {
			$smarty->assign('logined', 0);
			$member = t('member');
			$member->id = 0;
			$member->avatar = add_domain('/images/avatar.jpg');
			$smarty->assign('member', $member);
		}

		//var_dump($data);exit();
		$smarty->assign("data", $data);

		require_once(APP_PATH."/cart.php");
		$c = new cart();
		$carts = $c->total(false, true);
		$smarty->assign("cart_notify", $carts['quantity']);

		$smarty->assign($_GET);
		$smarty->assign($_POST);
		if (is_array($element)) $smarty->assign($element);

		$url = (isset($_REQUEST['url']) && trim($_REQUEST['url'])) ? trim($_REQUEST['url']) : '';
		$is_app = stripos($_SERVER['HTTP_USER_AGENT'], 'ruandao')===false ? 0 : 1;
		$is_wx = stripos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')===false ? 0 : 1;
		$is_mini = (isset($_REQUEST['is_mini']) && intval($_REQUEST['is_mini']) && $is_wx) ? intval($_REQUEST['is_mini']) : 0;
		$smarty->assign('url', $url);
		$smarty->assign('is_app', $is_app); //是否公司项目APP内打开网页
		$smarty->assign('is_wx', $is_wx);
		$smarty->assign('is_mini', $is_mini);
		$smarty->assign('app', $app);
		$smarty->assign('act', $act);
		$smarty->assign('web_title', WEB_TITLE);

		$gourl = (isset($_REQUEST['gourl']) && trim($_REQUEST['gourl'])) ? trim($_REQUEST['gourl']) : $gourl;
		$goalert = (isset($_REQUEST['goalert']) && trim($_REQUEST['goalert'])) ? trim($_REQUEST['goalert']) : $goalert;
		if (strlen($gourl)) {
			$html = '<meta charset="UTF-8"><script>';
			if (strlen($goalert)) $html .= "alert('{$goalert}');";
			$html .= "location.href = '{$gourl}';</script>";
			exit($html);
		}

		//weixin jssdk
		$goods_name = '';
		$goods_default_pic = '';
		$goods_desc = '';
		if ($app=='goods' && $act=='detail') {
			$goods_name = $data->name;
			$goods_desc = $data->description;
			$goods_default_pic = $data->pic;
		}
		//微信JSSDK
		$weixin_jssdk = new JSSDK(WX_APPID, WX_SECRET);
		$weixin_sign_package = $weixin_jssdk->getSignPackage();
		$smarty->assign('weixin_sign_package', $weixin_sign_package);
		$smarty->assign('share_title', WEB_TITLE);
		$smarty->assign('share_desc', '专业的劳务派遣、社保代理机构');
		$smarty->assign('share_img', 'http://huanchuang.softstao.com/images/logo.png');
		$smarty->assign('goods_name', $goods_name);
		$smarty->assign('goods_desc', $goods_desc);
		$smarty->assign('goods_default_pic', $goods_default_pic);
		
		$output = (isset($_REQUEST['output']) && trim($_REQUEST['output'])) ? trim($_REQUEST['output']) : '';
		if ($output=='json'){
			$vars = $smarty->getTemplateVars();
			unset($vars['output']);
			echo json_encode($vars);
			exit;
		}
		$smarty->display($template_file);
	} else {
		error_tip("Template does not exists.");
	}
}
